package com.suneee.enterprise.service.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.suneee.base.config.ServiceConfig;
import com.suneee.base.util.ContextHelper;
import com.suneee.base.util.HttpClientUtils;
import com.suneee.base.util.JsonUtil;
import com.suneee.cloud.admin.dao.AdministratorDao;
import com.suneee.cloud.admin.service.AdministratorService;
import com.suneee.context.page.Page;
import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.type.json.JsonUtils;
import com.suneee.enterprise.bean.EnterpriseSearchBean;
import com.suneee.enterprise.bean.OutMallCodeBean;
import com.suneee.enterprise.dao.EnterpriseDao;
import com.suneee.enterprise.entity.Enterprise;
import com.suneee.enterprise.service.EnterpriseService;
import com.suneee.logistic.dao.EnterpriseLogisticDao;
import com.suneee.logistic.dao.LogisticDao;
import com.suneee.logistic.entity.EnterpriseLogistics;
import com.suneee.logistic.entity.Logistic;
import com.suneee.resources.ProductError;
import com.suneee.sso.admin.entity.Administrator;


@Service("api-enterprise")
public class EnterpriseServiceImpl implements EnterpriseService {

	@Autowired
	private EnterpriseDao enterpriseDao;
	
	@Autowired
	private AdministratorService administratorService;
	
	@Autowired
	private AdministratorDao administratorDao;
	
	@Autowired
	private EnterpriseLogisticDao enterpriseLogisticDao;
	
	@Autowired
	private LogisticDao logisticDao;

	/**
	 * 企业的增加
	 */
	@Override
	@Transactional
	public Enterprise add(Enterprise enterprise) {
		Assert.notNull(enterprise.getName(), "企业名称");
		Assert.notNull(enterprise.getShortName(), "企业简称");
		Assert.notNull(enterprise.getType(), "企业类型");
		// Assert.notNull(enterprise.getBusinessLicense(), "营业执照");
		Assert.notNull(enterprise.getAddress(), "企业地址");
		Assert.notNull(enterprise.getLegalPerson(), "公司法人代表");
		Assert.notNull(enterprise.getEnterpriseMail(), "企业邮箱");
		Assert.notNull(enterprise.getTelephone(), "联系电话");
		
		Assert.notNull(enterprise.getCompanyCode(), "物流公司");
		
		Assert.notNull(enterprise.getOutMallCode(), "外部商城的企业编码");
		
		//调用ERP接口，验证外部企业编码是否有效
//		boolean isVisible = validateOutMallCode(enterprise.getOutMallCode());
//		if(!isVisible){
//			throw ErrorUtils.wrap(ProductError.OUTMALLCODE_INVALID);
//		}
		/*
		 * if (this.existsCode(enterprise.getEnterpriseCode())) { throw
		 * ErrorUtils.wrap(ProductError.ENTERPRISE_CODE_DUPLICATE); }
		 */
		if (enterpriseDao.existsName(enterprise.getName())) {
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_NAME_DUPLICATE);
		}
		if (enterpriseDao.existsShortName(enterprise.getShortName())) {
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_SHORTNAME_DUPLICATE);
		}
		if (enterpriseDao.existsMail(enterprise.getEnterpriseMail())) {
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_MAIL_DUPLICATE);
		}
		// 企业类型(客户:client 系统:system)
		if (!enterprise.getType().equals(Enterprise.CLIENT) && !enterprise.getType().equals(Enterprise.SYSTEM)) {
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_TYPE_NO);
		}
		// 获取当前创建时间
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		enterprise.setCreateTime(timestamp);

		enterprise.setEnabled(true);
//		enterprise.setReviewStatue(Enterprise.NO);
		enterprise.setReviewStatus(Enterprise.SUCCESS);//本期不做审核功能，默认为通过
		// 自动生成企业编码
		enterprise.setEnterpriseCode(this.totalCode());
		enterpriseDao.insert(enterprise);
		
		//插入企业默认物流
		EnterpriseLogistics enterpriseLogistics = new EnterpriseLogistics();
		enterpriseLogistics.setCompanyCode(enterprise.getCompanyCode());
		enterpriseLogistics.setEnterpriseCode(enterprise.getEnterpriseCode());
		enterpriseLogistics.setDefaults(true);
		Logistic logistic = logisticDao.select(enterprise.getCompanyCode());
		enterpriseLogistics.setCompanyName(logistic.getCompanyName());
		enterpriseLogisticDao.insert(enterpriseLogistics);
		
		
		/** 企业入驻后，调用企业管理员新增接口，后台自动生成企业管理员账号 **/
		Administrator admin = new Administrator();
		admin.setEmail(enterprise.getEnterpriseMail());
		admin.setEnterpriseCode(enterprise.getEnterpriseCode());
		admin.setMobile(enterprise.getTelephone());
		admin.setName(enterprise.getLegalPerson());
		admin.setEnabled("0");
		administratorService.addEnAdmin(admin);
		
		return enterprise;

	}
	
	/**
	 * 调用ERP接口,验证外部企业编码是否有效
	 * @param outMallCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private boolean validateOutMallCode(String outMallCode){
		Map<String,Object> map = new HashMap<String, Object>();
		boolean isVisible = false;
		String erpUrl = ContextHelper.getBean("serviceConfig", ServiceConfig.class).getErpUrl();
		OutMallCodeBean bean = new 	OutMallCodeBean();
		bean.setOutMallCode(outMallCode);
		Object obj = bean;
		try {
			String json = JsonUtils.writer().writeValueAsString(obj);
			String resultInfo= HttpClientUtils.postJson("", json,erpUrl); //调用接口验证外部商城编码
			
			Map<String,Object> resultMap  = (Map<String, Object>) JsonUtil.fromJson(resultInfo, map.getClass());
//			Integer code = (Integer) resultMap.get("code");
			String isEnable = (String)resultMap.get("isEnable");
			if("Y".equals(isEnable)){
				isVisible =  true;
			}else{
				isVisible = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isVisible;
	}

	/**
	 * 自动生成code
	 * 
	 * @return
	 */
	private String totalCode() {
		
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式
		String format = df.format(new Date());
		
		Random random = new Random();
		int i = random.nextInt(1000);
		
		String enterpriseCode = "qy" + format + i;
		// 1.获取当天已经插入几条企业数据+1
//		List<Enterprise> list = enterpriseDao.selectEnterpriseQuantity(enterpriseCode);
//
//		if (list != null && !list.isEmpty()) {
//			Enterprise enterpriseCodeLast = list.get(list.size() - 1);
//			String str = enterpriseCodeLast.getEnterpriseCode();
//			str = str.substring(10, str.length());
//			int code = Integer.parseInt(str);
//			String totalStr = totalStr(code);
//			enterpriseCode = enterpriseCode + totalStr;
//
//		} else {
//			enterpriseCode = enterpriseCode + "0001";
//		}
		return enterpriseCode;

	}

	/**
	 * 补零操作
	 * 
	 * @param total
	 * @return
	 */
	private String totalStr(int total) {
		String str = null;
		if (total <= 9) {
			str = "000" + String.valueOf(total + 1);
		} else if (total <= 99) {
			str = "00" + String.valueOf(total + 1);
		} else if (total <= 999) {
			str = "0" + String.valueOf(total + 1);
		} else {
			str = String.valueOf(total + 1);
		}
		return str;
	}

	/**
	 * 判断企业编码是否存在
	 */
	@Override
	public boolean existsCode(String enterpriseCode) {
		Assert.notNull(enterpriseCode, "企业编码");
		return enterpriseDao.existsCode(enterpriseCode);
	}

	/**
	 * enterprise.list 获取t_enterprise表中的符合条件的数据
	 */
	@Override
	public Page<Enterprise> find(EnterpriseSearchBean bean) {
		return enterpriseDao.find(bean);
	}

	/**
	 * 获取单条企业信息
	 */
	@Override
	public Enterprise get(String enterpriseCode) {
		Assert.notNull(enterpriseCode, "企业编码");
		if (this.existsCode(enterpriseCode)) {
			List<Enterprise> list = enterpriseDao.get(enterpriseCode);
			Enterprise enterprise = new Enterprise();
			if (list.size() > 0) {
				enterprise = list.get(0);
			}
			//获取企业默认物流
			EnterpriseLogistics enlogis = enterpriseLogisticDao.getDefaultLogistics(enterprise.getEnterpriseCode());
			if(enlogis != null){
				enterprise.setCompanyCode(enlogis.getCompanyCode());
			}
			return enterprise;
		} else {
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_DUPLICATE);
		}
	}

	/**
	 * 删除企业信息根据企业编码
	 */
	@Override
	@Transactional
	public void delete(String enterpriseCode) {
		Assert.notNull(enterpriseCode, "企业编码");
		if (this.existsCode(enterpriseCode)) {
			enterpriseDao.deleteByEnterpriseCode(enterpriseCode);
			administratorService.deleteAccount(enterpriseCode);
		} else {
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_DUPLICATE);

		}
	}

	/**
	 * 修改单条数据
	 */
	@Override
	public Enterprise update(Enterprise enterprise) {
		Assert.notNull(enterprise.getEnterpriseCode(), "企业编码");
		Assert.notNull(enterprise.getName(), "企业名称");
		Assert.notNull(enterprise.getShortName(), "企业简称");
		Assert.notNull(enterprise.getType(), "企业类型");
		Assert.notNull(enterprise.getAddress(), "企业地址");
		// Assert.notNull(enterprise.getBusinessLicense(), "营业执照");
		Assert.notNull(enterprise.getLegalPerson(), "公司法人代表");
		Assert.notNull(enterprise.getTelephone(), "联系电话");

		Enterprise old = this.get(enterprise.getEnterpriseCode());
		if (!old.getName().equals(enterprise.getName()) && enterpriseDao.existsName(enterprise.getName())) {
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_NAME_DUPLICATE);
		}
		if (!old.getShortName().equals(enterprise.getShortName())
				&& enterpriseDao.existsShortName(enterprise.getShortName())) {
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_SHORTNAME_DUPLICATE);
		}
		if (!old.getEnterpriseMail().equals(enterprise.getEnterpriseMail())
				&& enterpriseDao.existsMail(enterprise.getEnterpriseMail())) {
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_MAIL_DUPLICATE);
		}
		if (!this.existsCode(enterprise.getEnterpriseCode())) {
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_DUPLICATE);
		}

		// 企业类型(客户:client 系统:system)
		if (enterprise.getType().equals(Enterprise.CLIENT) || enterprise.getType().equals(Enterprise.SYSTEM)) {
			// 获取当前修改时间
			Timestamp timestamp = new Timestamp(System.currentTimeMillis());
			enterprise.setLastUpdateTime(timestamp);

			enterpriseDao.updateEnterprise(enterprise);
		}
		return enterprise;
	}

	/**
	 * 企业禁用
	 */
	@Override
	@Transactional
	public void disabled(String enterpriseCode) {
		enterpriseDao.disabledEnterprise(enterpriseCode);
		List<Administrator> list = administratorDao.getListByEnterpriseCode(enterpriseCode);
		for(Administrator obj : list){
			obj.setEnabled("0");
		}
		administratorDao.update(list);
	}

	/**
	 * 企业激活
	 */
	@Override
	@Transactional
	public void enabled(String enterpriseCode) {
		enterpriseDao.enabledEnterprise(enterpriseCode);
		List<Administrator> list = administratorDao.getListByEnterpriseCode(enterpriseCode);
		for(Administrator obj : list){
			obj.setEnabled("1");
		}
		administratorDao.update(list);
	}

	/**
	 * 企业审核(成功)
	 */
	@Override
	public void successAudit(Enterprise enterprise) {
		Assert.notNull(enterprise.getEnterpriseCode(), "企业编码");
		Assert.notNull(enterprise.getReviewDesctiption(), "审核描述");

		enterpriseDao.audit(enterprise.getEnterpriseCode(), Enterprise.SUCCESS, enterprise.getReviewDesctiption());
	}

	/**
	 * 企业审核(未通过)
	 */
	@Override
	public void failureAudit(Enterprise enterprise) {
		Assert.notNull(enterprise.getEnterpriseCode(), "企业编码");
		Assert.notNull(enterprise.getReviewDesctiption(), "审核描述");

		enterpriseDao.audit(enterprise.getEnterpriseCode(), Enterprise.FAILURE, enterprise.getReviewDesctiption());
	}

	@Override
	public Enterprise getByName(String name) {
		return enterpriseDao.getByName(name);
	}

}
